<script lang="ts" setup name="LoginForm">
import { ref, watch } from 'vue'
import useStore from '@/store'
import router from '@/router'
import Message from '@/components/message'
import { useField, useForm } from 'vee-validate'
import {useCountDown } from '@/utils/hooks'
const { user } = useStore()
const active = ref<'account' | 'mobile'>('account')

// 校验
const { validate, resetForm } = useForm({
  // 默认值
  initialValues:{
    account:'cdshi0006',
    password:'123456',
    isAgree:true,
    mobile:'13012345738',
    code:'123456'
  },
  // 校验字段的方法 => 只有return为true时表示校验通过
  validationSchema: {
    // 账号
    account(value: string) {
      if (!value) return '账号不能为空'
      if (!/^[a-zA-Z]\w{4,14}$/.test(value?.trim()))
        return '账号以字母开头5-15位字符'
      return true
    },
    // 密码
    password(value: string) {
      if (!value) return '密码不能为空'
      if (!/^\w{5,15}/.test(value?.trim())) return '密码5-15位字符'
      return true
    },
    // 复选框
    isAgree(value: boolean) {
      if (!value) return '请同意许可协议'
      return true
    },
    // 手机号
    mobile: (value: string) => {
      if (!value) return '请输入手机号'
      if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式错误'
      return true
    },
    // 验证码
    code: (value: string) => {
      if (!value) return '请输入验证码'
      if (!/^\d{6}$/.test(value)) return '验证码格式错误'
      return true
    },
  },
})

const { value: account, errorMessage: accountErrMsg } =
  useField<string>('account')
const { value: password, errorMessage: passwoedErrMsg } =
  useField<string>('password')
const { value: isAgree, errorMessage: isAgreeErrMsg } =
  useField<boolean>('isAgree')
const { value: mobile, errorMessage: mobileError,validate:validMobile } = useField<string>('mobile')
const { value: code, errorMessage: codeError } = useField<string>('code')

// 登录
const handleLogin = async () => {
  // 预校验
  const res = await validate()
  // if (!res.valid) return
  if(active.value==='account'){
    // 分开验证 账号|密码
    if(res.errors.account||res.errors.password||res.errors.isAgree) return
    await user.loginByAccount({
      account: account.value,
      password: password.value,
    })
  }else{
    // 分开验证 手机号|验证码
    if(res.errors.mobile||res.errors.code||res.errors.isAgree) return
    await user.loginByCode({mobile:mobile.value,code:code.value})
  }
    // 登录成功
    // 成功之后跳转至首页
    Message.success('登录成功')
    router.push('/')
  
}
// 侦听active 发生变化重置表单
watch(active, () => {
  resetForm()
})
// 发送验证码
let timer = -1
const mobileRef = ref<HTMLInputElement>()
const {time,start } = useCountDown()
const sendCode = async () => {
  // 在倒计时期间禁止重复倒计时
  if(time.value>0)return Message.warning(`请${time.value}s后发送`)
  // 发送验证码前验证手机号合法性 不合法聚焦input
  const { valid } = await validMobile()
  if (!valid) return mobileRef.value!.focus()
    await user.getCode(mobile.value)
    Message.success('验证码已发送')
  start()
}
</script>
<template>
  <div class="account-box">
    <div class="toggle">
      <a
        href="javascript:;"
        v-if="active !== 'account'"
        @click="active = 'account'"
      >
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="active = 'mobile'">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>

    <div class="form">
      <template v-if="active === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              type="text"
              placeholder="请输入用户名或手机号"
              v-model="account"
            />
          </div>
          <div class="error" v-if="accountErrMsg">
            <i class="iconfont icon-warning" />{{ accountErrMsg }}
          </div>
        </div>

        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input
              type="password"
              placeholder="请输入密码"
              v-model="password"
            />
          </div>
          <div class="error" v-if="passwoedErrMsg">
            <i class="iconfont icon-warning" />{{ passwoedErrMsg }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input type="text" v-model="mobile" placeholder="请输入手机号" />
          </div>
          <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />{{ mobileError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="text" v-model="code" placeholder="请输入验证码" />
            <span @click="sendCode" ref="mobileRef" class="code"
              >{{ time === 0 ? '发送验证码' : `${time}s后发送` }}</span
            >
          </div>
          <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />{{ codeError }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="isAgree">我已同意</XtxCheckbox>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeErrMsg">
          <i class="iconfont icon-warning" />{{ isAgreeErrMsg }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="handleLogin">登录</a>
    </div>

    <div class="action">
      <img
        src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
        alt=""
      />
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
